import 'package:shared_preferences/shared_preferences.dart';

class _Cache {
  SharedPreferences? _prefs;

  Future<void> init() async {
    _prefs = await SharedPreferences.getInstance();
  }

  Future<bool> setString(String key, String value) async {
    if (_prefs == null) await init();
    return await _prefs!.setString(key, value);
  }

  Future<bool> setDouble(String key, double value) async {
    if (_prefs == null) await init();
    return _prefs!.setDouble(key, value);
  }

  Future<bool> setInt(String key, int value) async {
    if (_prefs == null) await init();
    return await _prefs!.setInt(key, value);
  }

  Future<bool> setBool(String key, bool value) async {
    if (_prefs == null) await init();
    return await _prefs!.setBool(key, value);
  }

  Future<bool> setStringList(String key, List<String> value) async {
    if (_prefs == null) await init();
    return await _prefs!.setStringList(key, value);
  }

  Future<Map<String, dynamic>?> getMap(String key) async {
    if (_prefs == null) await init();
    return _prefs!.get(key) as Map<String, dynamic>;
  }

  Future<String?> getString(String key) async {
    if (_prefs == null) await init();
    return _prefs!.getString(key);
  }

  bool getBoolSync(String key) {
    return _prefs?.getBool(key) ?? false;
  }

  int? getIntSync(String key) {
    return _prefs?.getInt(key);
  }

  String? getStringSync(String key) {
    return _prefs?.getString(key);
  }

  Future<T?> get<T>(String key) async {
    if (_prefs == null) await init();
    var data = _prefs!.get(key);
    if (data == null) return null;
    return data as T;
  }

  T? getSync<T>(String key) {
    var data = _prefs?.get(key);
    if (data == null) return null;
    return data as T;
  }

  Future<bool> removeKey(String key) async {
    return await _prefs!.remove(key);
  }

  void clear() {
    _prefs!.clear();
  }
}

final _Cache cache = _Cache();
